package com.zhangx.study.demo.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @ClassName Mosquitto
 * @Description
 * @Author zhangx
 **/
@Slf4j
public class MosquittoApp {

    public static void main(String[] args) {
        String subTopic = "zhangx/#";
        log.info("订阅主题{}",subTopic);
        String broker = "tcp://10.10.10.190:2883";
        String clientId = "emqx_test";
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 保留会话
            connOpts.setCleanSession(false);

            // 设置回调
            client.setCallback(new PushCallback());

            // 建立连接
            log.info("Connecting to broker: " + broker);
//            client.connect();
            client.connect(connOpts);

            log.info("Connected");
//            System.out.println("Publishing message: " + content);

            // 订阅
            client.subscribe(subTopic);

        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}
